package cn.yzx.pethome.config;

import cn.yzx.pethome.annotation.PreAuthorize;
import cn.yzx.pethome.system.logininfo.domain.Logininfo;
import cn.yzx.pethome.system.role.mapper.RoleMapper;
import cn.yzx.pethome.system.role.service.IRoleService;
import cn.yzx.pethome.system.user.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自己定义的登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final String MSG = "{\"success\":false,\"msg\":\"noLogin\"}";
    private final String NO_PERMISSION = "{\"success\":false,\"msg\":\"noPermission\"}";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("我进来了哟");
        String toKen = request.getHeader("ToKen");
        if(toKen == null) {
            //ctrl + alt + m 抽取方法
            setErrorMsg(response,MSG);
            return false;
        }
        Object o = redisTemplate.opsForValue().get(toKen);
        if(o == null){
            setErrorMsg(response,"\"noLogin\"");
            return false;
        }
        //刷新
        redisTemplate.opsForValue().set(toKen,o,30, TimeUnit.MINUTES);

        List<String>permissionsByRoleIds = (List<String>)redisTemplate.opsForValue().get((toKen + "permission"));


        //2.1 哪些请求需要校验权限 （答：打了自定义注解PreAuthorize权限的方法）
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        //3.判断preAuthorize 是否有值
        if(preAuthorize == null){
            //3.2 没有，放行  公共资源不需要校验权限
            return true;
        }
        //3.1 有，校验是否有权限访问
        String sn = preAuthorize.value();//需要校验当前登录人，是否有权限访问该资源
        if(!permissionsByRoleIds.contains(sn)){
            setErrorMsg(response,NO_PERMISSION);
            return false;
        }

        return true;
    }

    private void setErrorMsg(HttpServletResponse response,String msg) throws IOException{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write(msg);
        writer.close();
    }
}
